package com.yzf.wisecoder.wisecodercommon.utils;

import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * @author jianghuiyong
 * @Description 图片压缩工具类
 * @date 2020/5/20 14:15
 */
@Slf4j
public class ImgCompressUtil {

    /**
     * 强制压缩/放大图片到固定的大小
     * @param inputStream 压缩文件
     * @return
     */
    public static BufferedImage resize(InputStream inputStream, int width, int height){
        //原图
        BufferedImage img = null;
        //压缩后图
        BufferedImage compressImg = null;
        try {
            img = ImageIO.read(inputStream);
            compressImg = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB );
            // 绘制缩小后的图
            compressImg.getGraphics().drawImage(img, 0, 0, width, height, null);
        } catch (IOException e) {
            log.error("图片压缩异常:{}", e.toString());
        }

        return compressImg;
    }

    /**
     * BufferedImage转InputStream
     * @param bimage
     * @return
     */
    public static InputStream getImageStream(BufferedImage bimage, String imgType){
        InputStream is = null;
        ByteArrayOutputStream bs = new ByteArrayOutputStream();
        ImageOutputStream imOut;
        try {
            imOut = ImageIO.createImageOutputStream(bs);
            ImageIO.write(bimage, imgType,imOut);
            is= new ByteArrayInputStream(bs.toByteArray());
        } catch (IOException e) {
            log.error("获取文件内容异常", e.toString());
        }
        return is;
    }
}
